import React from 'react';
import { mapConfig } from 'Constants/config';
import { SearchBar } from 'antd-mobile';
import { connect } from 'react-redux';
import { MAP_ALERT_LEVEL, BUSINESS_TYPE } from 'Constants/mapConstants';
import Api from 'Utils/api';
import dialog from 'Utils/dialog';
import * as routerActions from 'react-router-redux';
import './index.scss';

const itemArea = 1; // 企业区域
const itemType = 2; // 企业类型
const itemLevel = 3; // 企业等级

class Popup extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      selectItem: ''
    };
    this.changeClass = ::this.changeClass;
  }
  show(selectItem, data) {
    if (data.length > 0) {
      this.changeClass('hidden', 'active');
      this.setState({
        data,
        selectItem
      });
    }
  }
  hide() {
    this.changeClass('active', 'hidden');
  }
  changeClass(curerent, replace) {
    const maskEle = document.getElementById('popup-mask');
    const currentClass = maskEle.getAttribute('class');
    maskEle.setAttribute('class', currentClass.replace(curerent, replace));
  }
  handleSelect(selectData) {
    const { selectItem } = this.state;
    this.props.handleSelect(selectItem, selectData);
    this.hide();
  }
  render() {
    const { data } = this.state;
    return (
      <div className="mask-wrap hidden" id="popup-mask" >
        <div id="popup">
          <div className="mask-content">
            {
              data.map(item => (
                <div className="mask-item" key={item.id} onClick={this.handleSelect.bind(this, item)}>
                  { item.name }
                </div>
              ))
            }
          </div>
          <div className="btn-wrap" onClick={this.hide.bind(this)} >
            取消
          </div>
        </div>
      </div>
    )
  }
}

class ShiAnMap extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      deptData: [],
      searchValue: sessionStorage.getItem('organise') ? JSON.parse(sessionStorage.getItem('organise')) : {},
      selectDept: {},
      selectType: sessionStorage.getItem('selectType') ? JSON.parse(sessionStorage.getItem('selectType')) : BUSINESS_TYPE[0],
      selectLevel: sessionStorage.getItem('selectLevel') ? JSON.parse(sessionStorage.getItem('selectLevel')) : MAP_ALERT_LEVEL[3],
      mapData: []
    };
    this.LoadMapInfo = ::this.LoadMapInfo;
  }
  componentDidMount() {
    sessionStorage.setItem('height', window.innerHeight);
    this.initMap();
    this.initDeptInfo();
  }
  getIconUrl() {
    let url = '';
    const { selectType, selectLevel } = this.state;
    if (selectLevel.id === 1) {
      /* 预警 */
      url = selectType.alert_level1;
    } else if (selectLevel.id === 2) {
      /* 警示 */
      url = selectType.alert_level2;
    } else if (selectLevel.id === 3) {
      /* 告警 */
      url = selectType.alert_level3;
    } else if (selectLevel.id === 4) {
      /* 正常 */
      url = selectType.alert_normal;
    }
    url = `images/mapIcon/${url}`;
    return url;
  }
  initMap() {
    // 经纬度地图显示；
    this.map = new T.Map('map');
    // 双击放大地图；
    this.map.enableDoubleClickZoom();
    // 地图滚轮缩放；
    this.map.enableScrollWheelZoom();
    // 地图惯性拖拽；
    this.map.enableInertia();
    // 设置显示地图的中心点和级别
    this.map.centerAndZoom(new T.LngLat(mapConfig.longitude, mapConfig.latitude), 16);
  }
  initDeptInfo() {
    const api = new Api({
      method: 'GET',
      path: '/justices/dept',
      success: (res) => {
        const storageOrg = sessionStorage.getItem('selectDept') ? JSON.parse(sessionStorage.getItem('selectDept')) : '';
        this.setState({
          deptData: res,
          selectDept: storageOrg || (res.length > 0 ? res[0] : {})
        }, () => {
          this.handleMapInfo();
        });
      },
      error: (msg) => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => {},
          },
        ];
        dialog.open('提示', msg, buttons, 'center');
      }
    });
    api.run();
  }
  handleMapInfo() {
    const { searchValue, selectLevel, selectDept, selectType } = this.state;
    const query = {};
    query.offset = 0;
    query.limit = 10000;
    if (selectDept.name) { query.manage_gov_id = selectDept.id; }
    if (selectType.name) { query.category = selectType.name; }
    if (selectLevel.name) { query.level = selectLevel.id; }
    if (searchValue.name) { query.name_like = searchValue.name; }
    const api = new Api({
      method: 'GET',
      path: '/enterprises/warn_level',
      query,
      success: (res) => {
        this.setState({
          mapData: res.data_list
        }, () => {
          // 根据数据找到合适得地图视野
          if (this.state.mapData.length > 0) {
            const data = res.data_list.map(item => new T.LngLat(item.longitude, item.latitude));
            const newData = this.map.getViewport(data);
            this.map.panTo(new T.LngLat(newData.center.lng, newData.center.lat), newData.zoom);
          }
          this.LoadMapInfo();
        });
      },
      error: (msg) => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => {},
          },
        ];
        dialog.open('提示', msg, buttons, 'center');
      }
    });
    api.run();
  }
  LoadMapInfo() {
    const self = this;
    const { mapData, selectLevel } = this.state;
    this.map.clearOverLays();
    for (let i = 0, len = mapData.length; i < len; i++) {
      const icon = new T.Icon(
        {
          iconUrl: self.getIconUrl(), iconSize: new T.Point(24, 24), iconAnchor: new T.Point(12, 24)
        });

      // 向地图上添加自定义标注
      const marker = new T.Marker(
        new T.LngLat(mapData[i].longitude, mapData[i].latitude), { icon }
        );
      this.map.addOverLay(marker);

      marker.addEventListener('click', () => {
        this.map.clearOverLays();
        self.LoadMapInfo();
        // 添加信息窗口信息
        const infoContent = `
        <div class="info-content-wrap">
          <div class="info-row">
           <div class="info-col1">企业名称：</div>
           <div class="info-col2">${mapData[i].name || ''}</div>
          </div>
          <div class="info-row">
          <div class="info-col1">企业地点：</div>
           <div class="info-col2">${mapData[i].address || ''}</div>
          </div>
          <div class="info-row">
           <div class="info-col1">法人代表：</div>
           <div class="info-col2">${mapData[i].legal_entity || ''}</div>
          </div>
          <div class="info-row">
           <div class="info-col1">消费提示：</div>
           <div class="info-col2" style="color: ${`${selectLevel.color}`}">${selectLevel.name}</div>
          </div>
        </div>
        `;
        this.infoWin = new T.InfoWindow(infoContent, { minWidth: 100, autoPan: true });
        const lnglat = new T.LngLat(mapData[i].longitude, mapData[i].latitude);
        this.map.panTo(new T.LngLat(mapData[i].longitude, mapData[i].latitude), this.map.getZoom());
        this.infoWin.setLngLat(lnglat);
        this.infoWin.setOffset([0, -24]);
        this.map.addOverLay(this.infoWin);
      })
    }
  }
  handleItemClick(item, data) {
    this.Popup.show(item, data);
  }
  handleSelect(item, data) {
    sessionStorage.removeItem('organise');
    if (item === itemArea) {
      /* 选择区域 */
      this.setState({
        selectDept: data,
        searchValue: {}
      }, () => { this.handleMapInfo(); });
    } else if (item === itemType) {
      /* 选择类型 */
      this.setState({
        selectType: data,
        searchValue: {}
      }, () => { this.handleMapInfo(); });
    } else if (item === itemLevel) {
      /* 选择等级 */
      this.setState({
        selectLevel: data,
        searchValue: {}
      }, () => { this.handleMapInfo(); });
    }
  }
  handleFocus() {
    const { selectType, selectLevel, selectDept } = this.state;
    if (!selectDept.id) {
      return;
    }
    sessionStorage.setItem('selectType', JSON.stringify(selectType));
    sessionStorage.setItem('selectLevel', JSON.stringify(selectLevel));
    sessionStorage.setItem('selectDept', JSON.stringify(selectDept));
    this.props.dispatch(routerActions.push('/map/search'))
  }
  render() {
    const height = sessionStorage.getItem('height') ? parseInt(sessionStorage.getItem('height'), 10) : window.innerHeight;
    const { deptData, selectDept, selectType, selectLevel, searchValue } = this.state;
    return (
      <div className="shian-map-page" id="shian">
        <div className="map" id="map" style={{ height }} />
        <div className="top-search">
          <SearchBar
            placeholder="请输入"
            value={searchValue.name}
            onFocus={this.handleFocus.bind(this)}
          />
        </div>
        <div className="bottom-wrap">
          <div className="item-wrap">
            <div className="icon-wrap" onClick={this.handleItemClick.bind(this, itemArea, deptData)}>
              <div className="label">{selectDept.name || '选择区域'}</div>
              <img src="images/icon_business_area.png" alt="" />
            </div>
          </div>
          <div className="item-wrap">
            <div className="icon-wrap" onClick={this.handleItemClick.bind(this, itemType, BUSINESS_TYPE)}>
              <div className="label">{selectType.name || ''}</div>
              <img src="images/icon_business_type.png" alt="" />
            </div>
          </div>
          <div className="item-wrap">
            <div className="icon-wrap" onClick={this.handleItemClick.bind(this, itemLevel, MAP_ALERT_LEVEL)}>
              <div className="label">{selectLevel.name || ''}</div>
              <img src={`images/${selectLevel.icon}`} alt="" />
            </div>
          </div>
        </div>
        <Popup
          ref={(ref) => { this.Popup = ref }}
          handleSelect={this.handleSelect.bind(this)}
        />
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
  };
}
export default connect(mapStateToProps)(ShiAnMap);

